package com.cathaypacific.sample.auth

import android.app.Activity
import android.os.Bundle
import com.cathaypacific.facebook.login.utils.MetaUtils
import com.facebook.CallbackManager
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import com.facebook.FacebookException
import com.facebook.login.LoginResult
import com.facebook.FacebookCallback
import android.content.Intent
import com.cathaypacific.facebook.login.widget.LogOutListen
import com.facebook.AccessToken
import com.google.gson.Gson


class SocialSigninActivity : Activity() {
    val EMAIL = "email"
    val PUBLIC_PROFILE = "public_profile"
    val USER_FRIENDS = "user_friends"
    val FBId = "com.facebook.sdk.ApplicationId"
    val callbackManager = CallbackManager.Factory.create()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
    }

    private fun init() {
        val loggedIn = AccessToken.getCurrentAccessToken() == null
        btn_login.setReadPermissions(Arrays.asList(EMAIL, PUBLIC_PROFILE, USER_FRIENDS))
        tv_text.text = "appid:" + MetaUtils.getMeta(this, FBId)
        btn_login.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(loginResult: LoginResult?) {

                tv_result.text = Gson().toJson(loginResult)

            }

            override fun onCancel() {
                tv_result.text = "onCancel"
            }

            override fun onError(exception: FacebookException?) {
                tv_result.text = "onError" + exception?.message
            }
        }, object : LogOutListen {

            override fun onLogOut() {
                tv_result.text = "logOut";
            }
        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }
}